<?php
use think\facade\Db;
use think\facade\Session;
use think\facade\Request;
use think\facade\Cache;


//管理员登录日志
function adminLog($log_info)
{
    $admin_id = Session::get('admin_id') ? Session::get('admin_id') : 'null';
    $admin_id = !empty($admin_id) ? $admin_id : $admin_id;
    $add['admin_id'] = $admin_id;
    $add['log_info'] = $log_info;//操作类型
    $add['log_ip'] = clientIP();//客户端ip
    $add['log_browserType'] = GetBrowser();//浏览器
    $add['log_device'] = Request::isMobile() ? "手机" : "电脑";//设备
    $add['log_osName'] = GetOs();//设备类型
    $add['log_time'] = getTime();//日记时间
    Db::name('admin_log')->save($add);
}
//获取当前时间戳
function getTime(){
    return time();
}
/**
 * 递归读取文件夹文件
 * string $directory 目录路径
 * string $dir_name 显示的目录前缀路径
 * array $arr_file 是否删除空目录
 */
function getDirFile($directory, $dir_name='', &$arr_file = []) 
{
    if (!file_exists($directory)) {
        return false;
    }
    $mydir = dir($directory); 
    while($file = $mydir->read()){
        if((is_dir("$directory/$file")) AND ($file != ".") AND ($file != "..")){
            if ($dir_name) {
                getDirFile("$directory/$file", "$dir_name/$file", $arr_file);
            } else {
                getDirFile("$directory/$file", "$file", $arr_file);
            }
        }else if(($file != ".") AND ($file != "..")){
            if ($dir_name) {
                $arr_file[] = "$dir_name/$file";
            } else {
                $arr_file[] = "$file";
            }
        }
    }
    $mydir->close();
    return $arr_file;
}
/**
 * 格式化字节大小 
 * number $size      字节数
 * string $delimiter 数字和单位分隔符
 * string            格式化后的带单位的大小
 */
function format_bytes($size, $delimiter = '') 
{
    $units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB');
    for ($i = 0; $size >= 1024 && $i < 5; $i++) $size /= 1024;
    return round($size, 2) . $delimiter . $units[$i];
}
//允许发布文档的栏目列表
function allow_release_arctype($selected = 0, $allow_release_channel = [], $selectform = true , $iscacheKey = false) 
{
    $where = [];
    if (!is_array($selected)) {$selected = [$selected];}
    $cacheKey = json_encode($selected).json_encode($allow_release_channel).$selectform.json_encode($where);
    $select_html = Cache::get($cacheKey);//获取缓存
    if (empty($select_html) || false == $selectform || true == $iscacheKey) {
        //允许发布文档的模型
        $allow_release_channel = !empty($allow_release_channel) ? $allow_release_channel : config('pcfcms.allow_release_channel');
        //所有栏目分类
        $arctype_max_level = intval(config('pcfcms.arctype_max_level'));
        $where[] = ['c.status','=',1];
        $where[] = ['c.is_hidden','=',0];
        $fields = "c.id, c.parent_id, c.current_channel, c.typename, c.grade, count(s.id) as has_children, '' as children";
        $res = db::name('arctype')
             ->field($fields)
             ->alias('c')
             ->join('arctype s','s.parent_id = c.id','LEFT')
             ->where($where)
             ->group('c.id')
             ->order('c.parent_id asc, c.sort_order asc, c.id')
             ->select()->toArray();
        Cache::tag('arctype')->set($cacheKey, $res, ADMIN_CACHE_TIME);
        if (empty($res)) {return false;}
        //过滤掉第三级栏目属于不允许发布的模型下
        foreach ($res as $key => $val) {
            if ($val['grade'] == ($arctype_max_level - 1) && !in_array($val['current_channel'],$allow_release_channel)) {
                unset($res[$key]);
            }
        }
        //所有栏目列表进行层次归类
        $arr = group_same_key($res, 'parent_id');
        for ($i=0; $i < $arctype_max_level; $i++) {
            foreach ($arr as $key => $val) {
                foreach ($arr[$key] as $key2 => $val2) {
                    if (!isset($arr[$val2['id']])) {
                        $arr[$key][$key2]['has_children'] = 0;
                        continue;
                    }
                    $val2['children'] = $arr[$val2['id']];
                    $arr[$key][$key2] = $val2;
                }
            }
        }
        //过滤掉第二级不包含允许发布模型的栏目
        $nowArr = $arr[0];
        foreach ($nowArr as $key => $val) {
            if (!empty($nowArr[$key]['children'])) {
                foreach ($nowArr[$key]['children'] as $key2 => $val2) {
                    if (empty($val2['children']) && !in_array($val2['current_channel'], $allow_release_channel)) {
                        unset($nowArr[$key]['children'][$key2]);
                    }
                }
            }
            if (empty($nowArr[$key]['children']) && !in_array($nowArr[$key]['current_channel'], $allow_release_channel)) {
                unset($nowArr[$key]);
                continue;
            }
        }
        //组装成层级下拉列表框
        $select_html = '';
        if (false == $selectform) {
            $select_html = $nowArr;
        } else if (true == $selectform) {
            foreach ($nowArr AS $key => $val){
                $select_html .= '<option value="' . $val['id'] . '" data-grade="' . $val['grade'] . '" data-current_channel="' . $val['current_channel'] . '"';
                $select_html .= (in_array($val['id'], $selected)) ? ' selected="ture"' : '';
                if (!empty($allow_release_channel) && !in_array($val['current_channel'], $allow_release_channel)) {
                    $select_html .= ' disabled="true" style="background-color:#f5f5f5;"';
                }
                $select_html .= '>';
                if ($val['grade'] > 0){
                    $select_html .= str_repeat('&nbsp;', $val['grade'] * 4);
                }
                $select_html .= htmlspecialchars(addslashes($val['typename'])) . '</option>';
                if (empty($val['children'])) {
                    continue;
                }
                foreach ($nowArr[$key]['children'] as $key2 => $val2) {
                    $select_html .= '<option value="' . $val2['id'] . '" data-grade="' . $val2['grade'] . '" data-current_channel="' . $val2['current_channel'] . '"';
                    $select_html .= (in_array($val2['id'], $selected)) ? ' selected="ture"' : '';
                    if (!empty($allow_release_channel) && !in_array($val2['current_channel'], $allow_release_channel)) {
                        $select_html .= ' disabled="true" style="background-color:#f5f5f5;"';
                    }
                    $select_html .= '>';
                    if ($val2['grade'] > 0){
                        $select_html .= str_repeat('&nbsp;', $val2['grade'] * 4);
                    }
                    $select_html .= htmlspecialchars(addslashes($val2['typename'])) . '</option>';
                    if (empty($val2['children'])) {continue;}
                    foreach ($nowArr[$key]['children'][$key2]['children'] as $key3 => $val3) {
                        $select_html .= '<option value="'.$val3['id'].'" data-grade="'.$val3['grade'].'" data-current_channel="'.$val3['current_channel'].'"';
                        $select_html .= (in_array($val3['id'], $selected)) ? ' selected="ture"' : '';
                        if (!empty($allow_release_channel) && !in_array($val3['current_channel'], $allow_release_channel)) {
                            $select_html .= ' disabled="true" style="background-color:#f5f5f5;"';
                        }
                        $select_html .= '>';
                        if ($val3['grade'] > 0){
                            $select_html .= str_repeat('&nbsp;', $val3['grade'] * 4);
                        }
                        $select_html .= htmlspecialchars(addslashes($val3['typename'])).'</option>';
                    }
                }
            }
            Cache::tag('admin_archives_release')->set($cacheKey, $select_html);   
        }
    }
    return $select_html;
}
//获取全部的模型
function getChanneltypeList()
{
    $result = Cache::get('admin_channeltype_list_logic');
    if ($result == false){
        $result = db::name('channel_type')->column('*', 'id');
        Cache::tag('channeltype')->set('admin_channeltype_list_logic', $result, ADMIN_CACHE_TIME);
    }
    return $result;
}
/**
 * 替换指定的符号
 * array $arr 特殊字符的数组集合
 * string $replacement 符号
 * string $str 字符串
 */
function func_preg_replace($arr = [], $replacement = ',', $str = '')
{
    if (empty($arr)) {$arr = array('，');}
    foreach ($arr as $key => $val) {
        $str = preg_replace('/('.$val.')/', $replacement, $str);
    }
    return $str;
}

/**
 * 清除非站内链接
 * string $body  内容
 * array $allow_urls 允许的超链接
 */
function replace_links($body, $allow_urls = [])
{
    $host = request()->host(true);
    if (!empty($allow_urls)) {
        $allow_urls = array_merge([$host], $allow_urls);
    } else {
        $basic_body_allowurls = sysConfig('web.web_pcfcms');
        if (!empty($basic_body_allowurls)) {
            $allowurls = explode(PHP_EOL, $basic_body_allowurls);
            $allow_urls = array_merge([$host], $allowurls);
        } else {
            $allow_urls = [$host];
        }
    }
    $host_rule = join('|', $allow_urls);
    $host_rule = preg_replace("#[\n\r]#", '', $host_rule);
    $host_rule = str_replace('.', "\\.", $host_rule);
    $host_rule = str_replace('/', "\\/", $host_rule);
    $arr = '';
    preg_match_all("#<a([^>]*)>(.*)<\/a>#iU", $body, $arr);
    if( is_array($arr[0]) )
    {
        $rparr = array();
        $tgarr = array();
        foreach($arr[0] as $i=>$v)
        {
            if( $host_rule != '' && preg_match('#'.$host_rule.'#i', $arr[1][$i]) )
            {
                continue;
            } else {
                $rparr[] = $v;
                $tgarr[] = $arr[2][$i];
            }
        }
        if( !empty($rparr) )
        {
            $body = str_replace($rparr, $tgarr, $body);
        }
    }
    $arr = $rparr = $tgarr = '';
    return $body;
}
/**
 * 远程图片本地化
 * string $body 内容
 */
function remote_to_local($body = "")
{
    $web_basehost = sysConfig('web.web_basehost');
    $parse_arr = parse_url($web_basehost);
    $web_basehost = $parse_arr['scheme'].'://'.$parse_arr['host'];
    $basehost = request()->domain();
    $img_array = [];
    preg_match_all("/src=[\"|'|\s]([^\"|^\'|^\s]*?)/isU", $body, $img_array);
    $img_array = array_unique($img_array[1]);
    foreach ($img_array as $key => $val) {
        if(preg_match("/^http(s?):\/\/mmbiz.qpic.cn\/(.*)\?wx_fmt=(\w+)&/", $val) == 1){
            unset($img_array[$key]);
        }
    }
    $dirname = '/uploads/ueditor/'.date('Ymd/');
    //创建目录失败
    if(!file_exists($dirname) && !mkdir($dirname,0777,true)){
        return $body;
    }else if(!is_writeable($dirname)){
        return $body;
    }
    foreach($img_array as $key=>$value){
        $imgUrl = trim($value);
        if(preg_match("#".$basehost."#i", $imgUrl)){
            continue;// 本站图片
        }
        if($web_basehost != $basehost && preg_match("#".$web_basehost."#i", $imgUrl)){
            continue;// 根网址图片
        }
        if(!preg_match("#^http(s?):\/\/#i", $imgUrl)){
            continue;// 不是合法链接
        }
        $heads = @get_headers($imgUrl, 1);
        // 获取请求头并检测死链
        if (empty($heads)) {
            continue;
        } else if(!(stristr($heads[0],"200") && stristr($heads[0],"OK"))){
            continue;
        }
        // 图片扩展名
        $fileType = substr($heads['Content-Type'], -4, 4);
        if(!preg_match("#\.(jpg|jpeg|gif|png|ico|bmp)#i", $fileType)){
            if($fileType=='image/gif'){
                $fileType = ".gif";
            }else if($fileType=='image/png'){
                $fileType = ".png";
            }else if($fileType=='image/x-icon'){
                $fileType = ".ico";
            }else if($fileType=='image/bmp'){
                $fileType = ".bmp";
            }else{
                $fileType = '.jpg';
            }
        }
        $fileType = strtolower($fileType);
        $is_weixin_img = false;
        if(preg_match("/^http(s?):\/\/mmbiz.qpic.cn\/(.*)/", $imgUrl) != 1){
            $allowFiles = [".png", ".jpg", ".jpeg", ".gif", ".bmp", ".ico", ".webp"];
            if(!in_array($fileType,$allowFiles) || (isset($heads['Content-Type']) && !stristr($heads['Content-Type'],"image/"))){
                continue;
            }
        } else {
            $is_weixin_img = true;
        }
        ob_start();
        $context = stream_context_create(['http' => ['follow_location' => false ]]);
        readfile($imgUrl, false, $context);
        $img = ob_get_contents();
        ob_end_clean();
        preg_match("/[\/]([^\/]*)[\.]?[^\.\/]*$/",$imgUrl,$m);
        $file = [];
        $file['oriName'] = $m ? $m[1] : "";
        $file['filesize'] = strlen($img);
        $file['ext'] = $fileType;
        $file['name'] = Session::get('admin_id').'-'.dd2char(date("ymdHis").mt_rand(100,999)).$file['ext'];
        $file['fullName'] = $dirname.$file['name'];
        $fullName = $file['fullName'];
        if($file['filesize'] >= 20480000){
            continue;//检查文件大小是否超出限制
        }
        if(!(file_put_contents($fullName, $img) && file_exists($fullName))){ 
            continue;//移动文件
        }
        $fileurl = '/'.$file['fullName'];
        if ($is_weixin_img == true) {
            $fileurl .= "?";
        }
        print_water($fileurl);
        $body = str_replace($imgUrl, $fileurl, $body);
    }
    return $body;
}
/**
 * 给图片增加水印
 * string $imgpath 不带子目录的图片路径
 */
function print_water($imgpath = "")
{
    try {
        static $water = null;
        null === $water && $water = sysConfig('water');
        if (empty($imgpath) || $water['is_mark'] != 1) {
            return $imgpath;
        }
        $imgpath = preg_replace('#^(/[/\w]+)?(/public/uploads/|/uploads/)#i', '$2', $imgpath);
        $imgresource = ".".$imgpath;
        $image = \think\Image::open($imgresource);
        $return_data['mark_type'] = $water['mark_type'];
        if($image->width()>$water['mark_width'] && $image->height()>$water['mark_height']){
            if($water['mark_type'] == 'text'){
                $ttf = WWW_ROOT.'public/common/font/hgzb.ttf';
                if (file_exists($ttf)) {
                    $size = $water['mark_txt_size'] ? $water['mark_txt_size'] : 30;
                    $color = $water['mark_txt_color'] ? $water['mark_txt_color'] : '#000000';
                    if (!preg_match('/^#[0-9a-fA-F]{6}$/', $color)) {
                        $color = '#000000';
                    }
                    $transparency = intval((100 - $water['mark_degree']) * (127/100));
                    $color.= dechex($transparency);
                    $image->open($imgresource)->text($water['mark_txt'], $ttf, $size, $color, $water['mark_sel'])->save($imgresource);
                    $return_data['mark_txt'] = $water['mark_txt'];
                }
            }else{
                $water['mark_img'] = preg_replace('#^(/[/\w]+)?(/public/uploads/|/uploads/)#i', '$2', $water['mark_img']); // 支持子目录
                $waterPath = public_path().$water['mark_img'];
                $waterPath = str_replace("\/", "/", $waterPath);
                if (pcfPreventShell($waterPath) && file_exists($waterPath)) {
                    $quality = $water['mark_quality'] ? $water['mark_quality'] : 80;
                    $waterTempPath = dirname($waterPath).'/temp_'.basename($waterPath);
                    $image->open($waterPath)->save($waterTempPath, null, $quality);
                    $image->open($imgresource)->water($waterTempPath, $water['mark_sel'], $water['mark_degree'])->save($imgresource);
                    @unlink($waterTempPath);
                }
            }
        }
    } catch (\Exception $e) {}
}
/**
 * 资源管理删除图片
 * @param $image_id
 */
function delImage($image_id)
{
    foreach ($image_id as $key => $val) {
      $res = del_Image($val);
    }
    if ($res) {
        $result = ['code' => 1, 'msg' => '删除成功'];
        return $result;
    }else{
        $result = ['code' => 0, 'msg' => '删除失败'];
        return $result;
    }
}
function del_Image($image_id)
{
    $image = Db::name('images')->where('id',$image_id)->find();
    if ($image) {
        $res = Db::name('images')->where('id',$image_id)->delete();
        Db::name('common_pic')->where("pid",$image_id)->delete();
        if ($image['type'] == 'local') {
            if(!empty($image['path'])){
                if(empty(PUBLIC_ROOT)){
                   @unlink(WWW_ROOT.'public'.$image['path']);
                }else{
                   @unlink(WWW_ROOT.$image['path']);
                }
            }
        }
        if ($res) {
            return true;
        }else{
            return false;
        }
    }else {
        return false;
    }
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////






























/**
 * 反格式化字节大小
 * @param  number $size      格式化带单位的大小
 */
function unformat_bytes($formatSize)
{
    $size = 0;
    if (preg_match('/^\d+P/i', $formatSize)) {
        $size = intval($formatSize) * 1024 * 1024 * 1024 * 1024 * 1024;
    } else if (preg_match('/^\d+T/i', $formatSize)) {
        $size = intval($formatSize) * 1024 * 1024 * 1024 * 1024;
    } else if (preg_match('/^\d+G/i', $formatSize)) {
        $size = intval($formatSize) * 1024 * 1024 * 1024;
    } else if (preg_match('/^\d+M/i', $formatSize)) {
        $size = intval($formatSize) * 1024 * 1024;
    } else if (preg_match('/^\d+K/i', $formatSize)) {
        $size = intval($formatSize) * 1024;
    } else if (preg_match('/^\d+B/i', $formatSize)) {
        $size = intval($formatSize);
    }
    $size = strval($size);
    return $size;
}
/**
 * 格式化数据化手机号码
 * @param $mobile
 * @return string
 */
function format_mobile($mobile)
{
    return substr($mobile, 0, 5) . "****" . substr($mobile, 9, 2);
}

//获取客户端浏览器信息 
function GetBrowser()
{
    if(!empty($_SERVER['HTTP_USER_AGENT']))
    {
     $br = $_SERVER['HTTP_USER_AGENT'];
     if (preg_match('/MSIE/i',$br)){
       $br = 'MSIE';
     }
     elseif (preg_match('/Firefox/i',$br)){
       $br = 'Firefox';
     }elseif (preg_match('/Chrome/i',$br)){
       $br = 'Chrome';
     }elseif (preg_match('/Safari/i',$br)){
       $br = 'Safari';
     }elseif (preg_match('/Opera/i',$br)){
       $br = 'Opera';
     }else {
       $br = 'Other';
     }
     return ($br."浏览器");
    }else{
     return "获取浏览器信息失败！";
    }
}
//获取客户端操作系统信息包括win10
function GetOs()
{
    $agent = $_SERVER['HTTP_USER_AGENT'];
    $os = false;
    if (preg_match('/win/i', $agent) && strpos($agent, '95'))
    {
      $os = 'Windows 95';
    }
    else if (preg_match('/win 9x/i', $agent) && strpos($agent, '4.90'))
    {
      $os = 'Windows ME';
    }
    else if (preg_match('/win/i', $agent) && preg_match('/98/i', $agent))
    {
      $os = 'Windows 98';
    }
    else if (preg_match('/win/i', $agent) && preg_match('/nt 6.0/i', $agent))
    {
      $os = 'Windows Vista';
    }
    else if (preg_match('/win/i', $agent) && preg_match('/nt 6.1/i', $agent))
    {
      $os = 'Windows 7';
    }
    else if (preg_match('/win/i', $agent) && preg_match('/nt 6.2/i', $agent))
    {
      $os = 'Windows 8';
    }else if(preg_match('/win/i', $agent) && preg_match('/nt 10.0/i', $agent))
    {
      $os = 'Windows 10';#添加win10判断
    }else if (preg_match('/win/i', $agent) && preg_match('/nt 5.1/i', $agent))
    {
      $os = 'Windows XP';
    }
    else if (preg_match('/win/i', $agent) && preg_match('/nt 5/i', $agent))
    {
      $os = 'Windows 2000';
    }
    else if (preg_match('/win/i', $agent) && preg_match('/nt/i', $agent))
    {
      $os = 'Windows NT';
    }
    else if (preg_match('/win/i', $agent) && preg_match('/32/i', $agent))
    {
      $os = 'Windows 32';
    }
    else if (preg_match('/linux/i', $agent))
    {
      $os = 'Linux';
    }
    else if (preg_match('/unix/i', $agent))
    {
      $os = 'Unix';
    }
    else if (preg_match('/sun/i', $agent) && preg_match('/os/i', $agent))
    {
      $os = 'SunOS';
    }
    else if (preg_match('/ibm/i', $agent) && preg_match('/os/i', $agent))
    {
      $os = 'IBM OS/2';
    }
    else if (preg_match('/Mac/i', $agent) && preg_match('/PC/i', $agent))
    {
      $os = 'Macintosh';
    }
    else if (preg_match('/PowerPC/i', $agent))
    {
      $os = 'PowerPC';
    }
    else if (preg_match('/AIX/i', $agent))
    {
      $os = 'AIX';
    }
    else if (preg_match('/HPUX/i', $agent))
    {
      $os = 'HPUX';
    }
    else if (preg_match('/NetBSD/i', $agent))
    {
      $os = 'NetBSD';
    }
    else if (preg_match('/BSD/i', $agent))
    {
      $os = 'BSD';
    }
    else if (preg_match('/OSF1/i', $agent))
    {
      $os = 'OSF1';
    }
    else if (preg_match('/IRIX/i', $agent))
    {
      $os = 'IRIX';
    }
    else if (preg_match('/FreeBSD/i', $agent))
    {
      $os = 'FreeBSD';
    }
    else if (preg_match('/teleport/i', $agent))
    {
      $os = 'teleport';
    }
    else if (preg_match('/flashget/i', $agent))
    {
      $os = 'flashget';
    }
    else if (preg_match('/webzip/i', $agent))
    {
      $os = 'webzip';
    }
    else if (preg_match('/offline/i', $agent))
    {
      $os = 'offline';
    }
    else
    {
      $os = '未知操作';
    }
    return ($os."系统");
}
/**
 * 过滤XSS攻击
 */
function remove_xss($val) 
{
    $val = preg_replace('/([\x00-\x08,\x0b-\x0c,\x0e-\x19])/', '', $val);
    $search = 'abcdefghijklmnopqrstuvwxyz';
    $search .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $search .= '1234567890!@#$%^&*()';
    $search .= '~`";:?+/={}[]-_|\'\\';
    for ($i = 0; $i < strlen($search); $i++) {
        $val = preg_replace('/(&#[xX]0{0,8}'.dechex(ord($search[$i])).';?)/i', $search[$i], $val);
        $val = preg_replace('/(&#0{0,8}'.ord($search[$i]).';?)/', $search[$i], $val);
    }
    $ra1 = array('javascript', 'vbscript', 'expression', 'applet', 'meta', 'xml', 'blink', 'link', 'style', 'script', 'embed', 'object', 'iframe', 'frame', 'frameset', 'ilayer', 'layer', 'bgsound', 'title', 'base');
    $ra2 = array('onabort', 'onactivate', 'onafterprint', 'onafterupdate', 'onbeforeactivate', 'onbeforecopy', 'onbeforecut', 'onbeforedeactivate', 'onbeforeeditfocus', 'onbeforepaste', 'onbeforeprint', 'onbeforeunload', 'onbeforeupdate', 'onblur', 'onbounce', 'oncellchange', 'onchange', 'onclick', 'oncontextmenu', 'oncontrolselect', 'oncopy', 'oncut', 'ondataavailable', 'ondatasetchanged', 'ondatasetcomplete', 'ondblclick', 'ondeactivate', 'ondrag', 'ondragend', 'ondragenter', 'ondragleave', 'ondragover', 'ondragstart', 'ondrop', 'onerror', 'onerrorupdate', 'onfilterchange', 'onfinish', 'onfocus', 'onfocusin', 'onfocusout', 'onhelp', 'onkeydown', 'onkeypress', 'onkeyup', 'onlayoutcomplete', 'onload', 'onlosecapture', 'onmousedown', 'onmouseenter', 'onmouseleave', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'onmousewheel', 'onmove', 'onmoveend', 'onmovestart', 'onpaste', 'onpropertychange', 'onreadystatechange', 'onreset', 'onresize', 'onresizeend', 'onresizestart', 'onrowenter', 'onrowexit', 'onrowsdelete', 'onrowsinserted', 'onscroll', 'onselect', 'onselectionchange', 'onselectstart', 'onstart', 'onstop', 'onsubmit', 'onunload');
    $ra = array_merge($ra1, $ra2);
    $found = true;
    while ($found == true) {
        $val_before = $val;
        for ($i = 0; $i < sizeof($ra); $i++) {
            $pattern = '/';
            for ($j = 0; $j < strlen($ra[$i]); $j++) {
                if ($j > 0) {
                    $pattern .= '(';
                    $pattern .= '(&#[xX]0{0,8}([9ab]);)';
                    $pattern .= '|';
                    $pattern .= '|(&#0{0,8}([9|10|13]);)';
                    $pattern .= ')*';
                }
                $pattern .= $ra[$i][$j];
            }
            $pattern .= '/i';
            $replacement = substr($ra[$i], 0, 2)."<x>".substr($ra[$i], 2);
            $val = preg_replace($pattern, $replacement, $val);
            if ($val_before == $val) {
                $found = false;
            }
        }
    }
    return $val;
}
/**
 * 获取文章内容html中第一张图片地址
 * @param  string $html html代码
 * @return boolean
 */
function get_html_first_imgurl($html)
{
    $pattern = '~<img [^>]*[\s]?[\/]?[\s]?>~';
    preg_match_all($pattern, $html, $matches);//正则表达式把图片的整个都获取出来了
    $img_arr = $matches[0];//图片
    $first_img_url = "";
    if (!empty($img_arr)) {
        $first_img = $img_arr[0];
        $p="#src=('|\")(.*)('|\")#isU";//正则表达式
        preg_match_all ($p, $first_img, $img_val);
        if(isset($img_val[2][0])){
            $first_img_url = $img_val[2][0]; //获取第一张图片地址
        }
    }
    return $first_img_url;
}
/**
 * 过滤前后空格等多种字符
 * @param string $str 字符串
 * @param array $arr 特殊字符的数组集合
 * @return string
 */
function trim_space($str, $arr = array())
{
    if (empty($arr)) {
        $arr = array(' ', '　');
    }
    foreach ($arr as $key => $val) {
        $str = preg_replace('/(^'.$val.')|('.$val.'$)/', '', $str);
    }
    return $str;
}
/**
 * 在文档列表显示文档属性标识
 * @param array $archivesInfo 文档信息
 * @return string
 */
function showArchivesFlagStr($archivesInfo = [])
{
    $arr = [];
    if (!empty($archivesInfo['is_head'])) {
        $arr['is_head'] = [
            'small_name'   => '头条',
        ];
    }
    if (!empty($archivesInfo['is_recom'])) {
        $arr['is_recom'] = [
            'small_name'   => '推荐',
        ];
    }
    if (!empty($archivesInfo['is_special'])) {
        $arr['is_special'] = [
            'small_name'   => '特荐',
        ];
    }
    if (!empty($archivesInfo['is_b'])) {
        $arr['is_b'] = [
            'small_name'   => '加粗',
        ];
    }
    if (!empty($archivesInfo['is_litpic'])) {
        $arr['is_litpic'] = [
            'small_name'   => '图片',
        ];
    }
    if (!empty($archivesInfo['is_jump'])) {
        $arr['is_jump'] = [
            'small_name'   => '跳转',
        ];
    }
    return $arr;
}